
package com.sun.showcase.interceptor;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.sun.showcase.aop.ratelimit.LimitRate;
import com.sun.showcase.exception.OutLimitRateException;
import com.sun.showcase.strategy.limit.GuavaRateLimitStrategy;
import com.sun.showcase.strategy.limit.RateLimitStrategy;
import com.sun.showcase.utils.IPUtils;

/**
 * 限流
 */
@Component
public class LimitRateInterceptor extends HandlerInterceptorAdapter {
	@Autowired RateLimitStrategy rateLimitStrategy;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    	LimitRate annotation;
        if(handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(LimitRate.class);
        }else{
            return true;
        }

        if(annotation == null || annotation.rate()<=0){
            return true;
        }
        //以 ip为维度限制访问速率，也可改为userid
        String ip = IPUtils.getIpAddr(request);
        boolean res = rateLimitStrategy.doLimit(ip, annotation.rate());
        if(!res) {
        	throw new OutLimitRateException();
        }
        return true;
    }
   
    @Bean
    public RateLimitStrategy getReateLimit() {
    	return new GuavaRateLimitStrategy();
    }
}
